﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.BusinessService;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.FormPlugIn.ShengLian
{
    [Description("盛联销售订单单价插件"), HotUpdate]
    public class ShengLianSal : AbstractBillPlugIn
    {
        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            if (e.Field.Key.Equals("FQty"))
            {
                var cust = this.Model.DataObject["CustId"] as DynamicObject;
                int custId = cust == null ? 0 : Convert.ToInt32(cust["id"]);
                Entity entity = this.Model.BillBusinessInfo.GetEntity("FSaleOrderEntry");
                var mat = this.Model.GetEntityDataObject(entity, e.Row)["MaterialId"] as DynamicObject;
                int materialId = mat == null ? 0 : Convert.ToInt32(mat["id"]);
                DynamicObjectCollection priceInfo = GetPriceInfo(materialId, custId);
                if (priceInfo.Count == 0) { return; }
                decimal price = Convert.ToDecimal(priceInfo[0][0]);
                int ver = Convert.ToInt32(priceInfo[0][1]);
                this.Model.SetValue("FTaxPrice", price, e.Row);
                this.Model.SetValue("F_POSW_Ver", ver, e.Row);
                this.View.InvokeFieldUpdateService("FEntryTaxRate", e.Row);
                this.View.UpdateView("FTaxPrice");
                this.View.UpdateView("F_POSW_Ver");
            }

        }

        private DynamicObjectCollection GetPriceInfo(int materialId, int custId)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT TOP 1 F_POSW_JSHJ,F_POSW_Ver FROM POSW_t_Cbfx WHERE F_POSW_CUSTID={0} AND F_POSW_MaterialId={1} AND FDOCUMENTSTATUS='C' ORDER BY F_POSW_Ver DESC ", custId, materialId);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }
    }
}
